package com.jiyi.activity.datainput.jm;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.activity.datainput.DIQxsqActivity;
import com.jiyi.activity.datainput.DISignMemberActivity;
import com.jiyi.activity.datainput.DIUserInfoCheckActivity;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.CommonAdapter;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.bean.datainput.DataInputBaseBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.DISQQXEvent;
import com.jiyi.inteface.ClearEditTextInterface;
import com.jiyi.inteface.OnRcvScrollListener;
import com.jiyi.inteface.WebApi;
import com.jiyi.widget.ClearEditText;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/3/30.
 */

public class JMDataViewActivity extends ActivityBase implements SwipeRefreshLayout.OnRefreshListener{

    /* 头部 */
    @BindView(R.id.tvBack)
    TextView tvBack;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvSearch)
    TextView tvSearch;

    @BindView(R.id.ivHint)
    ImageView ivHint;
    LayoutInflater inflater;
    @BindView(R.id.mainList)
    RecyclerView mListView;
    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.etSearch)
    ClearEditText etSearch;
    EmptyWrapper adapter;
    int type;
    private List<DataInputBaseBean> dataList = new ArrayList<DataInputBaseBean>();
    Dialog dialog;

    // 是否刷新模式
    boolean isRefresh = false;
    int pageNo = 1;// 页码
    private final int LOAD_DATA = 5; // 加载数据事件
    private boolean loadfinish = true; // 指示数据是否加载完成
    // 要被删除的任务
    int deletePosition = -1;
    // 要被删除的BID
    String deleteBid = "";

    private String[] datas = {"签到记录", "审核"};
    List<String> popDatas = Arrays.asList("签到记录", "审核");

    PopupWindow mPopupWindow;

    int assessCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_input_list);
        ButterKnife.bind(this);
        this.inflater = LayoutInflater.from(this);
        init();
    }

    private void init() {
        setTop();
        initViewState();
        setAdapter();
        getData();
        EventBus.getDefault().register(this);

    }

    @Subscribe
    public void onDISQQXEvent(DISQQXEvent dISQQXEvent) {
        if (dISQQXEvent.assess == 1) {
            // 主管
            setTop();
        } else if (dISQQXEvent.assess == 2) {
            // 调查员
            Intent intent = new Intent(this,JMAddMainActivity.class);
            startActivity(intent);
        }
    }

    private void initViewState() {
        // 设置输入法的搜索事件
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH
                        || actionId == EditorInfo.IME_ACTION_DONE) {
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

                    Log.e("onEditorAction  ", "   done ");
                    onRefresh();
                    return true;
                }
                return false;
            }
        });
        etSearch.setClearEditTextInterface(new ClearEditTextInterface() {

            @Override
            public void onClear() {
                onRefresh();
            }
        });
    }

    private void setTop() {
        tvTitle.setText("高层建筑消防安全评估系统");
        Drawable searchDraw;

        if (UserInfoUtil.getCurrentUserAcessRole() == 1) {
            searchDraw = getResources().getDrawable(R.mipmap.icon_more);
            searchDraw.setBounds(0, 0, searchDraw.getMinimumWidth(),
                    searchDraw.getMinimumHeight());
            tvSearch.setCompoundDrawables(null, null, searchDraw, null);
            tvSearch.setText("");
            tvSearch.setTextSize(10);
            ivHint.setVisibility(View.VISIBLE);
        } else {
            searchDraw = getResources().getDrawable(R.mipmap.icon_qxsq);
            searchDraw.setBounds(0, 0, searchDraw.getMinimumWidth(),
                    searchDraw.getMinimumHeight());
            tvSearch.setCompoundDrawables(null, searchDraw, null, null);
            tvSearch.setText("权限设置");
            tvSearch.setTextSize(10);
            ivHint.setVisibility(View.GONE);
        }

    }

    private void setAdapter() {
        // 设置refreshLayout的监听
        refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
                Color.GREEN);
        refreshLayout.setOnRefreshListener(this);

        mListView.setLayoutManager(new LinearLayoutManager(this));
        mListView.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL_LIST, getResources()
                .getDrawable(R.drawable.drvice_10_white)));

        // 初始化适配器
        CommonAdapter commonAdapter = new CommonAdapter<DataInputBaseBean>(
                this, R.layout.item_input_build, dataList) {
            @Override
            protected void convert(ViewHolder holder,
                                   final DataInputBaseBean t, final int position) {
                holder.setText(R.id.tvAddress, t.getAddress());
                holder.setText(R.id.tvName, t.getName());
                holder.setOnClickListener(R.id.root, new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(v.getContext(),
                                JMDataInputActivity.class);
                        intent.putExtra("type", 1);
                        intent.putExtra("build_no", t.getBuild_info_id());
                        intent.putExtra("canViewReport", true);
                        startActivity(intent);
                    }
                });
            }
        };

        adapter = new EmptyWrapper(commonAdapter);

        View emptyView = inflater.inflate(R.layout.empty_view_text_and_image,
                null, false);
        ImageView ivEmptyTip = (ImageView) emptyView
                .findViewById(R.id.ivEmptyTip);
        TextView tvEmptyTip = (TextView) emptyView
                .findViewById(R.id.tvEmptyTip);
        ivEmptyTip.setImageResource(R.mipmap.tip_empty_huodong);
        tvEmptyTip.setText(R.string.NO_DATA);
        adapter.setEmptyView(emptyView);

        mListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        mListView.addOnScrollListener(new OnRcvScrollListener() {
            @Override
            public void onBottom() {
                super.onBottom();
                if (loadfinish) {
                    Log.e("加载到底部 pageNo = ", pageNo + "");
                    Log.e("加载到底部 list size = ", dataList.size() + "");
                    loadMore();
                }

            }
        });
    }

    void loadMore() {
        isRefresh = false;
        mHandler.sendEmptyMessage(LOAD_DATA);
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        pageNo = 1;
        mHandler.sendEmptyMessage(LOAD_DATA);
    }

    /**
     * 处理中心
     */
    Handler mHandler = new Handler() {
        public void dispatchMessage(android.os.Message msg) {
            switch (msg.what) {
                case LOAD_DATA:
                    if (loadfinish) {
                        loadfinish = false;
                        getData();
                    }
                    break;
                default:
                    break;
            }
        }

        ;
    };

    private void getData() {
        Map<String, String> params = new HashMap<String, String>();
        params.put(AppConfig.ACCESS_TOKEN,
                UserInfoUtil.getCurrentUserAccessToken());
        params.put("page", pageNo + "");
        params.put("build_name", etSearch.getText().toString());
        VolleyRequest.StringRequestPost(this, WebApi.DATA_INPUT_LIST,
                "", params, new StringInterface(this) {

                    @Override
                    public void stringSuccess(String result) {
                        try {
                            JSONObject obj = new JSONObject(result);
                            String status = obj.getString("status");
                            String info = obj.getString("info");
                            if (status.equals("200")) {
                                String data = obj.getString("data");
                                JSONObject data_obj = new JSONObject(data);
                                assessCount = Integer.parseInt(data_obj.getString("assessCount"));
                                if (UserInfoUtil.getCurrentUserAcessRole() == 1 && assessCount > 0) {
                                    ivHint.setVisibility(View.VISIBLE);
                                } else {
                                    ivHint.setVisibility(View.GONE);
                                }

                                String projectList = data_obj
                                        .getString("projectList");

                                List<DataInputBaseBean> temp = new Gson()
                                        .fromJson(
                                                projectList,
                                                new TypeToken<List<DataInputBaseBean>>() {
                                                }.getType());
                                if (isRefresh) {
                                    dataList.clear();
                                }

                                if (temp.size() > 0) {
                                    dataList.addAll(temp);
                                    pageNo++;
                                } else {

                                }
                                adapter.notifyDataSetChanged();
                                loadfinish = true; // 加载完成
                            } else if (status.equals("404")
                                    && info.contains("尚未登录")) {
                                ToastUtil.getInstances().showMsg(
                                        "尚未登录或该用户在其他地方登录，请重新登录！");
                                // 清除环信登录
                                UserHelp.getInstance().clearUser(
                                        AppBase.Context, true);
                                return;
                            } else {
                                ToastUtil.getInstances().showMsg(info);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } finally {
                            refreshLayout.setRefreshing(false);
                        }
                    }

                    @Override
                    public void stringError(VolleyError error) {
                        refreshLayout.setRefreshing(false);
                        ToastUtil.getInstances().showMsg(
                                R.string.err_http_response);
                    }
                });
    }

    @OnClick({R.id.tvSearch,R.id.tvBack})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.tvBack:
                finish();
                break;
            case R.id.tvSearch:
                if (UserInfoUtil.getCurrentUserAcessRole() == 1) {
                    if (mPopupWindow == null)
                    {
// TODO: 2016/5/17 构建一个popupwindow的布局
                        View popupView = getLayoutInflater().inflate(
                                R.layout.showpop, null);

                        // TODO: 2016/5/17 为了演示效果，简单的设置了一些数据，实际中大家自己设置数据即可，相信大家都会。
                        ListView lsvMore = (ListView) popupView
                                .findViewById(R.id.lsvMore);
//                    lsvMore.setAdapter(new ArrayAdapter<String>(getActivity(),
//                            R.layout.item_pop_list, datas));

                        com.jiyi.adapter.CommonAdapter commonAdapter =  new com.jiyi.adapter.CommonAdapter(this,popDatas,R.layout.item_pop_hint_list) {
                            @Override
                            public void convert(com.jiyi.adapter.ViewHolder holder, Object o) {
                                holder.setText(R.id.state_name,o.toString());

                                if (holder.getPosition() == 1 && assessCount>0)
                                {
                                    holder.setVisible(R.id.ivHint,true);
                                }
                                else
                                {
                                    holder.setVisible(R.id.ivHint,false);

                                }
                            }
                        };

                        lsvMore.setAdapter(commonAdapter);

                        lsvMore.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                            @Override
                            public void onItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {
                                Intent intent;
                                if (position == 0) {
                                    // 签到记录
                                    intent = new Intent(JMDataViewActivity.this,
                                            DISignMemberActivity.class);
                                    startActivity(intent);
                                } else {
                                    // 审核
                                    intent = new Intent(JMDataViewActivity.this,
                                            DIUserInfoCheckActivity.class);
                                    startActivity(intent);
                                }
                                mPopupWindow.dismiss();

                            }
                        });

                        // TODO: 2016/5/17 创建PopupWindow对象，指定宽度和高度
                        mPopupWindow = new PopupWindow(popupView,
                                ViewGroup.LayoutParams.WRAP_CONTENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT, true);
                        // TODO: 2016/5/17 设置动画
                        mPopupWindow.setAnimationStyle(R.style.AnimFade);
                        // TODO: 2016/5/17 设置背景颜色
                        mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color
                                .parseColor("#F8F8F8")));
                        // TODO: 2016/5/17 设置可以获取焦点
                        mPopupWindow.setFocusable(true);
                        // TODO: 2016/5/17 设置可以触摸弹出框以外的区域
                        mPopupWindow.setOutsideTouchable(true);
                        // TODO：更新popupwindow的状态
                        mPopupWindow.update();
                        // TODO: 2016/5/17 以下拉的方式显示，并且可以设置显示的位置
                        mPopupWindow.showAsDropDown(view, 0, 20);
                    }
                    else
                    {
                        mPopupWindow.showAsDropDown(view, 0, 20);
                    }

                } else {
                    intent = new Intent(JMDataViewActivity.this, DIQxsqActivity.class);
                    startActivity(intent);
                }
                break;

            default:
                break;
        }
    }
}
